package com.xinongbest.mall.service.impl;

import com.xinongbest.mall.common.Constant;
import com.xinongbest.mall.exception.ImoocMallException;
import com.xinongbest.mall.exception.ImoocMallExceptionEnum;
import com.xinongbest.mall.filter.UserFilter;
import com.xinongbest.mall.model.dao.CartMapper;
import com.xinongbest.mall.model.dao.OrderItemMapper;
import com.xinongbest.mall.model.dao.OrderMapper;
import com.xinongbest.mall.model.dao.ProductMapper;
import com.xinongbest.mall.model.dto.CartDto;
import com.xinongbest.mall.model.dto.OrderRequestDto;
import com.xinongbest.mall.model.pojo.Order;
import com.xinongbest.mall.model.pojo.OrderItem;
import com.xinongbest.mall.model.pojo.Product;
import com.xinongbest.mall.service.OrderService;
import com.xinongbest.mall.util.OrderCodeFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    CartMapper cartMapper;

    @Autowired
    ProductMapper productMapper;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createOrder(OrderRequestDto orderRequestDto) {
        Integer userId = UserFilter.currentUser.getId();
        List<CartDto> cartDtoList = cartMapper.selectList(userId);
        // 查出用户购物车中商品
        if (!CollectionUtils.isEmpty(cartDtoList)) {
            // 过滤是选中的商品
            cartDtoList = cartDtoList.stream().filter(
                    cartDto -> cartDto.getSelected().equals(Constant.CartProductStatus.CHECKED)).collect(Collectors.toList()
            );
        }
        // 购物车中没有选中的商品
        if (CollectionUtils.isEmpty(cartDtoList)) {
            throw new ImoocMallException(ImoocMallExceptionEnum.CART_EMPTY);
        }
        // 购物车不为空：则校验库存、是否存在、是否上架
        validateProductStatus(cartDtoList);
        // 购物车商品转换为订单对象
        List<OrderItem> orderItems = cartListToOrderItemList(cartDtoList);
        // 修改商品库存
        if (!CollectionUtils.isEmpty(orderItems)) {
            for (OrderItem orderItem : orderItems) {
                Product product = productMapper.selectByPrimaryKey(orderItem.getProductId());
                int number = product.getStock() - orderItem.getQuantity();
                if (number < 0) {
                    throw new ImoocMallException(ImoocMallExceptionEnum.CREATE_FAILED);
                } else {
                    product.setStock(number);
                    productMapper.updateByPrimaryKeySelective(product);
                }
            }
        }
        // 删除购物车中商品
        cleanCart(cartDtoList);
        // 生成订单编号
        String orderCode = OrderCodeFactory.getOrderCode(Long.valueOf(userId));
        // 设置订单信息
        Order order = new Order();
        order.setOrderNo(orderCode);
        order.setUserId(userId);
        order.setTotalPrice(orderTotalPrice(cartDtoList));
        order.setReceiverName(orderRequestDto.getReceiverName());
        order.setReceiverAddress(orderRequestDto.getReceiverAddress());
        order.setReceiverPhone(orderRequestDto.getReceiverPhone());
        order.setOrderStatus(Constant.OrderStatusEnum.NOT_PAID.getCode());
        order.setPaymentType(1);
        order.setPostage(0);
        // 插入订单表
        orderMapper.insertSelective(order);
        // 订单商品入表
        for (int j = 0; j < orderItems.size(); j++) {
            OrderItem orderItem = orderItems.get(j);
            orderItem.setOrderNo(orderCode);
            orderItemMapper.insertSelective(orderItem);
        }
        return orderCode;
    }

    /**
     * 计算订单总价格
     *
     * @param cartDtoList
     * @return
     */
    private Integer orderTotalPrice(List<CartDto> cartDtoList) {
        Integer totalPrice = 0;
        for (CartDto cartDto : cartDtoList) {
            Integer productPrice = cartDto.getQuantity() * cartDto.getPrice();
            totalPrice += productPrice;
        }
        return totalPrice;
    }

    /**
     * 清空已经下单的购物车商品
     *
     * @param cartDtoList
     */
    private void cleanCart(List<CartDto> cartDtoList) {
        cartDtoList.forEach(cartDto -> cartMapper.deleteByPrimaryKey(cartDto.getId()));
    }

    /**
     * 购物车商品转换为订单列表对象
     *
     * @param cartDtoList
     * @return
     */
    private List<OrderItem> cartListToOrderItemList(List<CartDto> cartDtoList) {
        List<OrderItem> orderItemList = new ArrayList<>();
        OrderItem orderItem;
        for (CartDto cartDto : cartDtoList) {
            orderItem = new OrderItem();
            orderItem.setProductId(Integer.parseInt(cartDto.getProductId()));
            orderItem.setQuantity(cartDto.getQuantity());
            orderItem.setProductName(cartDto.getProductName());
            orderItem.setProductImage(cartDto.getProductImage());
            orderItem.setUnitPrice(cartDto.getPrice());
            orderItemList.add(orderItem);
        }
        return orderItemList;
    }

    /**
     * 用户下单校验购物车中的选中商品的状态
     *
     * @param cartDtoList
     */
    private void validateProductStatus(List<CartDto> cartDtoList) {
        for (CartDto cartDto : cartDtoList) {
            Product product = productMapper.selectByPrimaryKey(Integer.parseInt(cartDto.getProductId()));
            if (product == null || product.getStatus().equals(Constant.SaleStatus.NOT_SALE)) {
                throw new ImoocMallException(ImoocMallExceptionEnum.NOT_SALE);
            }
            if (cartDto.getQuantity() > product.getStock()) {
                throw new ImoocMallException(ImoocMallExceptionEnum.NOT_ENOUGH);
            }
        }
    }

    /**
     * 生成二维码
     *
     * @param orderNo
     * @return
     */
    public String qrcode(String orderNo) {
        return null;
    }
}
